import 'dart:convert';
import 'dart:typed_data';
import 'dart:async';

void main() async {
  // JSON 解码
  var jsonString = '''
    [
      {"score": 40},
      {"score": 80}
    ]
  ''';

  var scores = jsonDecode(jsonString);
  assert(scores is List);

  var firstScore = scores[0];
  assert(firstScore is Map);
  assert(firstScore['score'] == 40);

  // JSON 编码
  var scoresList = [
    {'score': 40},
    {'score': 80},
    {'score': 100, 'overtime': true, 'special_guest': null},
  ];

  var jsonText = jsonEncode(scoresList);
  assert(
    jsonText ==
        '[{"score":40},{"score":80},'
            '{"score":100,"overtime":true,'
            '"special_guest":null}]',
  );

  // UTF8 解码
  List<int> utf8Bytes = [
    0xc3, 0x8e, 0xc3, 0xb1, 0xc5, 0xa3, 0xc3, 0xa9,
    0x72, 0xc3, 0xb1, 0xc3, 0xa5, 0xc5, 0xa3, 0xc3,
    0xae, 0xc3, 0xb6, 0xc3, 0xb1, 0xc3, 0xa5, 0xc4,
    0xbc, 0xc3, 0xae, 0xc5, 0xbe, 0xc3, 0xa5, 0xc5,
    0xa3, 0xc3, 0xae, 0xe1, 0xbb, 0x9d, 0xc3, 0xb1,
  ];

  var funnyWord = utf8.decode(utf8Bytes);
  assert(funnyWord == 'Îñţérñåţîöñåļîžåţîờñ');

  // 模拟 inputStream 行分割
  var mockLines = Stream<String>.fromIterable([
    'hello',
    'world',
    'Îñţérñåţîöñåļîžåţîờñ',
  ]);
  await for (final line in mockLines) {
    print('Got ${line.length} characters from stream');
  }
  print('file is now closed');

  // UTF8 编码
  Uint8List encoded = Uint8List.fromList(utf8.encode('Îñţérñåţîöñåļîžåţîờñ'));
  assert(encoded.length == utf8Bytes.length);
  for (int i = 0; i < encoded.length; i++) {
    assert(encoded[i] == utf8Bytes[i]);
  }
}